<script setup>
import {inject, ref} from "vue";
import {instance} from '@/util/request.js';

//获取cookie数据
function getCookie(cookieName) {
  const strCookie = document.cookie;
  const cookieList = strCookie.split(';');
  for (let i = 0; i < cookieList.length; i++) {
    const arr = cookieList[i].split('=');
    if (cookieName === arr[0].trim()) {
      return arr[1];
    }
  }
  return '';
}

let props = defineProps({
  connect: {
    type: Function
  }
});

let loginStatus = ref('检查登录状态中...');
instance.get('/login/is', {
}).then(res => {
  const btn = document.getElementById("btn");
  if (res!=='') {
    loginStatus.value = "已登陆：" + res;
    btn.textContent = "已登录";
    btn.disabled = true;
    props.connect();
  } else {
    loginStatus.value = "未登录...";
    btn.textContent = "登录";
    btn.disabled = false;
  }
}).catch(err => {
  console.log(err);
});
const userList = [
  {
    username: 'admin',
    password: 'admin'
  },
  {
    username: 'lisi',
    password: '123456'
  }
];
let userIndex = ref(0);

function login() {
  var user = userList[userIndex.value];
  // websocket.send(JSON.stringify({
  //   type: '2',
  //   username: user.username,
  //   password: user.password,
  // }));
  instance.get('/login', {
    params: {
      username: user.username,
      password: user.password,
    }
  }).then(res => {
    const btn = document.getElementById("btn");
    if (res) {
      loginStatus.value = "登陆成功"
      btn.textContent = "已登录";
      btn.disabled = true;
      props.connect();
    } else {
      loginStatus.value = "账户不存在或密码错误！";
      btn.textContent = "重新登录";
    }
  }).catch(err => {
    console.log(err);
  });
}
</script>
<template>
  <div class="login">
    <h2>登录框</h2>
    <div style="width: 100%; height: 20px; line-height: 20px">{{loginStatus}}</div>
    <div class="radio">
      <input type="radio" name="user" :value="0" v-model="userIndex"><div>admin</div>
      <input type="radio" name="user" :value="1" v-model="userIndex"><div>lisi</div>
    </div>
    <div>账号：{{userList[userIndex].username}}&emsp;密码：{{userList[userIndex].password}}</div>
    <button id="btn" style="width: 100%" @click="login" disabled>登录</button>
  </div>
</template>
<style scoped>
.login {
  background-color: rgba(250,250,253,1);
  width: 400px;
  height: 200px;
  margin: 10px auto;
  padding: 10px;
  box-shadow: 0 0 8px 0 rgba(150,150,150,1);
  border-radius: 10px;
}

.radio {
  width: 100%;
  height: 20px;
}
.radio input {
  width: 20px;
  height: 20px;
  float: left;
}
.radio div {
  height: 20px;
  margin: 0 5px;
  line-height: 20px;
  user-select: none;
  float: left;
}
</style>